#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os
import sys
import time
import hashlib

json_file = "/opt/app/open-falcon/storage/passwd"

def get_md5():
    filename = '/etc/passwd'
    md5_result = {}
    if os.path.isfile(filename):
      fp=open(filename,'rb')
      contents=fp.read()
      fp.close()
      md5_result['md5'] = hashlib.md5(contents).hexdigest()
    else:
        print('file not exists')
    return md5_result

def create_record(value):
    record = {}
    record['Metric']      = "etc.passwd"
    record['Endpoint']    = os.uname()[1]
    record['Timestamp']   = int(time.time())
    record['Step']        = 60
    record['Value']       = value
    record['CounterType'] = 'GAUGE'
    record['TAGS']        = ''
    return record

def get_previous_md5():
    with open(json_file,'r') as load_f:
        load_dict = json.load(load_f)
        return load_dict

if __name__ == '__main__':
    if os.path.exists(json_file):
        data=[]
        md5_value = get_md5().get('md5')
        previous_md5_value = get_previous_md5().get('md5')
        if md5_value == previous_md5_value:
            value = 1
        else:
            value = 0
        data.append(create_record(value))
        print json.dumps(data)
    with open(json_file,"w") as f:
        json.dump(get_md5(),f)
